﻿using System;
using System.IO;
using System.Net;
using System.Text;
using Harvest.API.Model;

namespace Harvest.API
{

    /// <summary>
    /// 
    /// </summary>
    public partial class Wrapper
    {

        private readonly string _domain;
        private readonly string _userName;
        private readonly string _password;


        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="domain">The subdomain to logon to, i.e. subdomain.harvestapp.com.</param>
        /// <param name="userName">The email address.</param>
        /// <param name="password">Your password. Harvest uses HTTP Basic Auth.</param>
        public Wrapper(string domain, string userName, string password)
        {
            _domain = domain;
            _userName = userName;
            _password = password;
        }


        private string Request(WebRequestMethodEnum method, string action)
        {
            return Request(method, action, null);
        }
        private string Request(WebRequestMethodEnum method, string action, string data)
        {
            var request = WebRequest.Create("http://" + _domain + ".harvestapp.com/" + action) as HttpWebRequest;
            if (request != null)
            {
                request.Headers.Add("Authorization", "Basic #" + Convert.ToBase64String(Encoding.ASCII.GetBytes(_userName + ":" + _password)));
                request.Accept = "application/xml";
                request.ContentType = "application/xml";
                request.Method = method.ToString().ToUpper();
                if (data != null)
                {
                    var buffer = Encoding.ASCII.GetBytes(data);
                    request.ContentLength = buffer.Length;
                    var postData = request.GetRequestStream();
                    postData.Write(buffer, 0, buffer.Length);
                    postData.Close();
                }
                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        var reader = new StreamReader(response.GetResponseStream());
                        return reader.EndOfStream ? null : reader.ReadToEnd();
                    }
                }
            }
            return null;
        }

    }
}
